<!doctype html>
<html>

<head>
  <title>Record Challenge</title>
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
  <script src="../components/platform/platform.js"></script>
  <link rel="import" href="../components/core-header-panel/core-header-panel.html">
  <link rel="import" href="../components/core-toolbar/core-toolbar.html">
  <link rel="import" href="../components/font-roboto/roboto.html">
  <link rel="import" href="../components/google-map/google-map.html">
  <link rel="import" href="../components/paper-button/paper-button.html">
  <link rel="import" href="../components/paper-tabs/paper-tabs.html">
  <link rel="import" href="../components/paper-dialog/paper-dialog.html">
  <link rel="import" href="../components/paper-dialog/paper-dialog-transition.html">
  <link rel="import" href="../components/paper-input/paper-input.html">
  <link rel="import" href="challenge-map.html">
  <style>
  html,body {
    height: 100%;
    margin: 0;
    background-color: #E5E5E5;
    font-family: 'RobotoDraft', sans-serif;
  }
  .container {
    width: 80%;
    margin: 50px auto;
  }
  @media (min-width: 481px) {
    #tabs {
      width: 200px;
    }
    .container {
      width: 400px;
    }
  }
  core-header-panel {
    height: 100%;
    overflow: auto;
    -webkit-overflow-scrolling: touch;
  }
  core-toolbar {
    background: #03a9f4;
    color: white;
  }
  #tabs {
    width: 100%;
    margin: 0;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }
  google-map {
    display: block;
    height: 600px;
  }
  challenge-map {
    display: block;
    height: 90%;
  }
  button-bar {
    display: block;
    vertical-align: bottom;
  }
  </style>

</head>

<script>
  // This function adapted from http://www.html5rocks.com/en/tutorials/geolocation/trip_meter/#toc-step6
  // Calculates distance in meters.
  function calculateDistance(lat1, lon1, lat2, lon2) {
  var R = 6371; // km
  var dLat = (lat2 - lat1).toRad();
  var dLon = (lon2 - lon1).toRad();
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
  Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
  Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d * 1000;
  }
  Number.prototype.toRad = function() {
  return this * Math.PI / 180;
  }
</script>

<polymer-element name="record-page">
  <template>
    <style>
      challenge-map {
        display: block;
        height: 90%;
      }
      button-bar {
        display: block;
      }
    </style>

    <challenge-map id="record_map" challenge="{{ challenge }}" user_position="{{ user_position }}" flex></challenge-map>
    <div horizontal layout>
      <paper-button label="Add Point"
		    raisedButton
		    flex
		    on-click="{{ doAddPoint }}"></paper-button>
      <paper-button label="Start Recording"
		    id="record_button"
		    raisedButton
		    flex
		    on-click="{{ toggleRecording }}"></paper-button>
      <paper-button label="Save Challenge" raisedButton flex
        on-click="{{ showSaveChallengeDialog }}"></paper-button>
    </div>
    <paper-dialog id="save_dialog" heading="Save challenge" transition="paper-dialog-transition-bottom">
      <paper-input id="challenge_name" floatingLabel label="Challenge name"></paper-input>
      <paper-button label="Cancel" dismissive></paper-button>
      <paper-button label="Save" affirmative autofocus on-click="{{ doUpload }}"></paper-button>
    </paper-dialog>
    <core-ajax
      id="upload_ajax"
      url="http://bright-petal-676.appspot.com/challenge"
      method="POST"
      response="{{ response }}"
      on-core-response="{{ onResponse }}">
    </core-ajax>
  </template>
  <script>
    Polymer('record-page', {
      continuously_recording: false,
      challenge: {checkpoints: []},
      addLastPointToChallenge: function() {
        if (this.last_pos) {
          if (this.challenge && this.challenge.checkpoints.length > 0) {
            if (this.last_pos.timestamp - this.last_checkpoint_timestamp < 3) {
              return;
            }
            var checkpoint = this.challenge.checkpoints[this.challenge.checkpoints.length-1];
            var last_pos_dist = calculateDistance(this.last_pos.coords.latitude,
                                                  this.last_pos.coords.longitude,
                                                  checkpoint.latitude,
                                                  checkpoint.longitude);
            if (last_pos_dist < 10.0) {
              return;
            }
          }

          // TODO(alsu): don't add points that are too close to the last checkpoint
          var checkpoint = {latitude: this.last_pos.coords.latitude,
                            longitude: this.last_pos.coords.longitude,
                            accuracy: this.last_pos.coords.accuracy};

          this.challenge.checkpoints.push(checkpoint);
	  this.last_checkpoint_timestamp = this.last_pos.timestamp;
        }
      },
      "doAddPoint": function() {
        this.addLastPointToChallenge();
      },
      "toggleRecording": function() {
        this.continuously_recording = !this.continuously_recording;
        if (this.continuously_recording) {
          this.$.record_button.label = "Stop Recording";
        } else {
          this.$.record_button.label = "Start Recording";
        }
      },
      ready: function() {
        this.$.record_map.centerOnCurrentPosition();
      },
      user_positionChanged: function(old_pos, new_pos) {
        this.last_pos = new_pos;
        if (this.continuously_recording) {
          this.addLastPointToChallenge();
        }
      },
      showSaveChallengeDialog: function() {
//        if (this.challenge.checkpoints.length == 0)
//          return;
        this.$.save_dialog.toggle();
      },
      doUpload: function() {
        var content = JSON.stringify(this.challenge);
        var title = this.$.challenge_name.value;
        var upload = {Title: title, Content:content};
        this.$.upload_ajax.body = JSON.stringify(upload);
        this.$.upload_ajax.go();
        console.log(JSON.stringify(upload));
      },
      onResponse: function(e, details) {
        console.log(details.response);
        window.location.href = "index.html";
      },
    })
  </script>
</polymer-element>

<body unresolved touch-action="auto">
  <record-page/>
</body>

</html>
